package com.cpkso.buss.backend.trade.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.cpkso.buss.backend.trade.vo.StatisticsConditionVo;
import com.cpkso.buss.backend.trade.vo.StatisticsListVo;

/**
 * @author wrzhxy@qq.com
 * @date 2018年5月17日
 */
public class StatisticationDaoImpl implements StatisticationDao {
	private final static String BEDEPRIVE = "select new com.cpkso.buss.backend.trade.vo.StatisticsListVo("
			+ "sum(sellerPrice - buyerPrice), "
			+ "sum((sellerPrice - buyerPrice) * user.charge)"
			+ ") from TbOrder";
	/** 
     * 持久化上下文 
     */
	@PersistenceContext
	@Autowired
    private EntityManager entityManager;
//    public StatisticationDaoImpl(Class<T> domainClass, EntityManager em) {  
//        super(domainClass, em);  
//        this.entityManager = em;  
//    }
    
	@Override
	public StatisticsListVo bedeprive(StatisticsConditionVo sc) {
		StringBuffer hql = new StringBuffer(BEDEPRIVE + " where 1=1");
		List<Object> params = new ArrayList<>();
		if (sc.getUserId() != null) {
			hql.append(" and user.id=?");
			params.add(sc.getUserId());
        } else if (StringUtils.hasText(sc.getUsername())){
        	hql.append(" and user.name like?");
        	params.add("%" + sc.getUsername() + "%");
        }
        if (sc.getBeginDate() != null && sc.getEndDate() != null) {
        	// 买家号下单时间是否在某时段之间
        	hql.append(" and buyerTime between ? and ?");
        	params.add(sc.getBeginDate());
        	params.add(sc.getEndDate());
        }
        String sql = hql.toString();
        Query query = entityManager.createQuery(sql);
        for (int i = 0; i < params.size(); i++) {
        	query.setParameter(i, params.get(i));
        }
        
		return (StatisticsListVo) query.getResultList().get(0);
	}

}
